Grokking Oracle Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Oracle Easy
Count Number of Pairs With Absolute Difference K (easy)
Solution: Count Number of Pairs With Absolute Difference K
Degree of an Array (easy)
Solution: Degree of an Array
Find Subsequence of Length K With the Largest Sum (easy)
Solution: Find Subsequence of Length K With the Largest Sum
Rectangle Overlap (easy)
Solution: Rectangle Overlap
Remove All Adjacent Duplicates In String (easy)
Solution: Remove All Adjacent Duplicates In String
Island Perimeter (easy)
Solution: Island Perimeter
Climbing Stairs (easy)
Solution: Climbing Stairs
Move Zeroes (easy)
Solution: Move Zeroes
Excel Sheet Column Title (easy)
Solution: Excel Sheet Column Title
Valid Parentheses (Easy)
Solution: Valid Parentheses
Oracle Medium
Longest Palindromic Substring (medium)
Solution: Longest Palindromic Substring
Single Element in a Sorted Array (medium)
Solution: Single Element in a Sorted Array
Pairs of Songs With Total Durations Divisible by 60 (medium)
Solution: Pairs of Songs With Total Durations Divisible by 60
Search a 2D Matrix II (medium)
Solution: Search a 2D Matrix II
Minimize Maximum of Array (medium)
Solution: Minimize Maximum of Array
Asteroid Collision (medium)
Solution: Asteroid Collision
Combination Sum (medium)
Solution: Combination Sum
Binary Tree Right Side View (medium)
Solution: Binary Tree Right Side View
Sort Colors (medium)
Solution: Sort Colors
Group Anagrams (Medium)
Solution: Group Anagrams
Decode String (Medium)
Solution: Decode String
Number of Islands (medium)
Solution: Number of Islands
Binary Tree Zigzag Level Order Traversal (medium)
Solution: Binary Tree Zigzag Level Order Traversal
Longest Common Subsequence (medium)
Solution: Longest Common Subsequence
Rotting Oranges (medium)
Solution: Rotting Oranges
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Delete Node in a BST (medium)
Solution: Delete Node in a BST
Remove Duplicate Letters (medium)
Solution: Remove Duplicate Letters
Longest Substring Without Repeating Characters (medium)
Solution: Longest Substring Without Repeating Characters (medium)
Search in Rotated Array (medium)
Solution: Search in Rotated Array
Spiral Matrix (medium)
Solution: Spiral Matrix
Container With Most Water (Medium)
Solution: Container With Most Water
3Sum (medium)
Solution: 3Sum
Simplify Path (medium)
Solution: Simplify Path
Next Permutation (medium)
Solution: Next Permutation
Basic Calculator II (medium)
Solution: Basic Calculator II
Merge Intervals (medium)
Solution: Merge Intervals
Restore IP Addresses (medium)
Solution: Restore IP Addresses
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Validate Binary Search Tree (medium)
Solution: Validate Binary Search Tree
Oracle Hard
Integer to English Words (hard)
Solution: Integer to English Words
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Merge K Sorted Lists (hard)
Solution: Merge K Sorted Lists
Max Points on a Line (hard)
Solution: Max Points on a Line
Sudoku Solver (hard)
Solution: Sudoku Solver
Longest Valid Parentheses (hard)
Solution: Longest Valid Parentheses
Remove Nth Node From End of List (Medium)
Solution: Remove Nth Node From End of List
Median of Two Sorted Arrays (hard)
Solution: Median of Two Sorted Arrays
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Solution: Sudoku Solver

Problem Statement

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  • Each of the digits 1-9 must occur exactly once in each row.
  • Each of the digits 1-9 must occur exactly once in each column.
  • Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

The '.' character indicates empty cells.

Example 1:
Input:

            {'5', '3', '.', '.', '7', '.', '.', '.', '.'},
            {'6', '.', '.', '1', '9', '5', '.', '.', '.'},
            {'.', '9', '8', '.', '.', '.', '.', '6', '.'},
            {'8', '.', '.', '.', '6', '.', '.', '.', '3'},
            {'4', '.', '.', '8', '.', '3', '.', '.', '1'},
            {'7', '.', '.', '.', '2', '.', '.', '.', '6'},
            {'.', '6', '.', '.', '.', '.', '2', '8', '.'},
            {'.', '.', '.', '4', '1', '9', '.', '.', '5'},
            {'.', '.', '.', '.', '8', '.', '.', '7', '9'}

Output:

            {'5'', '3'', '4'', '6'', '7'', '8'', '9'', '1'', '2''},
            {'6'', '7'', '2'', '1'', '9'', '5'', '3'', '4'', '8''},
            {'1'', '9'', '8'', '3'', '4'', '2'', '5'', '6'', '7''},
            {'8'', '5'', '9'', '7'', '6'', '1'', '4'', '2'', '3''},
            {'4'', '2'', '6'', '8'', '5'', '3'', '7'', '9'', '1''},
            {'7'', '1'', '3'', '9'', '2'', '4'', '8'', '5'', '6''},
            {'9'', '6'', '1'', '5'', '3'', '7'', '2'', '8'', '4''},
            {'2'', '8'', '7'', '4'', '1'', '9'', '6'', '3'', '5''},
            {'3'', '4'', '5'', '2'', '8'', '6'', '1'', '7'', '9''}

Explanation: The given output is the only valid Sudoku solution.

Constraints:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] is a digit or '.'
  • It is guaranteed that the input board has only one solution.

Solution

To solve the Sudoku puzzle, we use a backtracking approach. The key idea is to fill each empty cell with numbers from 1 to 9 and validate if the number can fit into the cell without violating the Sudoku rules. The rules are that each number must be unique in its row, column, and 3x3 sub-box. If a number fits, we proceed to the next empty cell recursively. If we encounter a cell where no number fits, we backtrack by resetting the previous cell and trying the next possible number. This process continues until the entire board is filled correctly.

This approach works because it explores all possible combinations and backtracks whenever it encounters a wrong combination, ensuring that we eventually find a solution if one exists. The efficiency is maintained by the early pruning of invalid paths, thus reducing unnecessary computations.

Step-by-Step Algorithm

  1. Initialization:

    • Define a helper function isValid to check if a number can be placed in a given cell without violating the Sudoku rules.
    • Define the main function solveSudoku that takes the board as input and calls the recursive solve function to fill the board.
  2. Validation Helper Function:

    • For a given cell (row, col) and number num, iterate over each cell in the same row, column, and 3x3 sub-box.
    • Check if the number num already exists in the same row, column, or sub-box.
    • Return True if num does not exist in any of these, otherwise return False.
  3. Recursive Solver Function:

    • Iterate over each cell in the board.
    • If an empty cell (denoted by .) is found, try placing each number from 1 to 9 in the cell.
    • Use the isValid function to check if the number can be placed in the cell.
    • If valid, place the number in the cell and recursively call the solve function.
    • If the recursive call returns True, the board is solved, so return True.
    • If placing the number does not lead to a solution, backtrack by resetting the cell to . and try the next number.
    • If no number from 1 to 9 can be placed in the cell, return False to indicate a dead end.
  4. Completion:

    • If the entire board is filled without conflicts, the solve function returns True.
    • The solveSudoku function then returns the solved board.

Code

Java
Saved to Cloud

. . . .

Time Complexity

since the board size is fixed, the time complexity is , as there is no variable input.

Though let's discuss the number of operations needed:

Let's consider one row where we have 9 cells to fill. There are not more than 9 possibilities for the first number to put, not more than 9×8 for the second one, not more than 9×8×7 for the third one, and so on. In total, that results in not more than possibilities for just one row; this means not more than operations in total.

If we compare the brutefore and backtracking algorithms:

  • = 1966270504755529136180759085269121162831034509442147669273154155379663911968099 for the brute force,

  • and =109110688415571316480344899355894085582848000000000 for the standard backtracking, i.e. the number of operations is reduced in times!

Space Complexity

The board size is fixed, and the space is used to store the board containing 81 cells, hence the time complexity is .

Sudoku Solver (hard)
Longest Valid Parentheses (hard)
Mark as Completed

On this page

Problem Statement

Solution

Step-by-Step Algorithm

Code

Time Complexity

Space Complexity